<template>
	<view class="tow-column-container">
		<MySearch v-if="showSearch" class="fixed-search" @searchQuery="searchQuery" />
		<!-- 列表 -->
		<scroll-view class="container" scroll-y @scroll="handleScroll" @scrolltolower="onLower"
			style="height: calc(100vh - 120rpx);">
			<view class="grid" v-if="data&&data.length" :style="{marginTop:!showSearch?'0': '80rpx',}">
				<view v-for="(item, index) in data" :key="index" :id="'media-' + index" class="media-item"
					@click="goDetail(item)">
					<!-- 视频图片切换 -->
					<!-- 默认显示图片
					<image v-if="!item.isPlaying" :src="item.img" class="media" mode="aspectFill"></image>
					进入中间区域后播放视频
					#ifdef H5
					<view v-else :id="'video-' + index" class="video-container media"></view>
					#endif 
					#ifdef APP-PLUS
					<video id="myVideo" :src="item.video" :poster="videoInfo.img" play-strategy=2 enable-play-gesture
						show-mute-btn autoplay :control="false" class="media"></video>
					#endif -->


					<image :src="item.img" class="media" mode="aspectFill"></image>
					<view class="name">{{item.name}}</view>
				</view>
			</view>
			<view v-else class="empty">
				<image src="@/static/images/empty.png" mode="aspectFit" style="width: 100%;"></image>
			</view>
		</scroll-view>
		<tui-toast ref="toast"></tui-toast>
		<MyUseOut :showModal="isUseOut" @close="isUseOut=false" />
	</view>
</template>

<script>
	import Hls from "hls.js";
	import DPlayer from "dplayer";
	import MySearch from '@/components/MySearch/MySearch.vue'
	import {
		historyList,
		collectList,
		videoList,
		configTypes
	} from '@/api/home.js'
	export default {
		name: "twoColumn",
		data() {
			return {
				isUseOut: false,
				tabShow: false,
				tabScroll: 0,
				data: [],
				tabIndex: 0,
				page: 1,
				count: 0,
				showSearch: true,
				userInfo: {},
				videoPlayers: {},
				pageType: '',
				querys: {}
			}
		},
		onUnload() {
			// 页面销毁时移除监听，防止重复绑定
			uni.$off('closeModal');
		},
		onLoad(options) {
			this.userInfo = this.$store.state.user.user
			if (options.type) {
				if (options.type == 'history') {
					uni.setNavigationBarTitle({
						title: '观影记录'
					});
					this.getHistoryList(this.userInfo._id)
				} else {
					uni.setNavigationBarTitle({
						title: '收藏记录'
					});
					this.getCollectList(this.userInfo._id)
				}
				this.showSearch = false;
				this.pageType = options.type
			} else {
				uni.setNavigationBarTitle({
					title: '更多影片'
				});
				this.showSearch = true;

				this.getList();
				this.pageType = 'more'
			}
			// 如果是从本页面的MyUseOut弹框进入三种增加次数的页面去了，并且增加成功后，再跳转到本页面要默认关闭弹窗
			uni.$on('closeModal', data => {
				this.isUseOut = data
			})
		},
		onShow() {},
		methods: {
			searchQuery(val) {
				this.querys = val
				this.data = []
				this.page = 1
				this.getList()
			},
			// 获取历史记录列表
			getHistoryList(id) {
				historyList({
					page: this.page,
					userId: id
				}).then(res => {
					this.data.push(...res.data.data);
					this.count = res.data.count;
					uni.stopPullDownRefresh();
				});
			},
			// 收藏记录列表
			getCollectList(id) {
				collectList({
					page: this.page,
					_id: id
				}).then(res => {
					this.data.push(...res.data.data);
					this.count = res.data.count;
					uni.stopPullDownRefresh();
				});
			},
			// 获取更多
			getList() {
				videoList({
					page: this.page,
					...this.querys
				}).then(res => {
					this.data.push(...res.data.data);
					this.count = res.data.count;
					uni.stopPullDownRefresh();
				});
			},
			// 分类数据到底
			onLower() {
				if (this.data.length < this.count) {
					this.page += 1;
					switch (this.pageType) {
						case 'history':
							this.getHistoryList(this.userInfo._id)
							break;
						case 'more':
							this.getList();
							break;
						case 'collect':
							this.getCollectList(this.userInfo._id)
							break;
					}
				} else {
					this.showTips()
				}
			},
			goDetail(item) {
				if (!uni.getStorageSync('infinite')) {
					this.isUseOut = true
					return
				}
				let id = ''
				switch (this.pageType) {
					case 'history':
						id = item.vidId
						break;
					case 'more':
						id = item._id
						break;
					case 'collect':
						id = item.vidId
						break;
				}
				uni.navigateTo({
					url: "/pages/watchMovie/videos?id=" + id
				});
			},
			showTips(e) {
				let options = {
					title: '我是有底线的啦~',
					icon: false
				};
				//需等组件初始化完成，确认已获取到组件实例
				this.$refs.toast && this.$refs.toast.show(options);
			},
			// 获取类型数据
			doGetTabs() {
				configTypes().then(res => {
					this.tabs = [{
						name: "热门推荐"
					}, ...res.data, {
						_id: "-1",
						name: "其他"
					}];
					this.doGetRecommendVideos();
				});
			},
			// 前往搜索页面
			onToSearch() {
				uni.navigateTo({
					url: "/pages/watchMovie/search"
				});
			},
			// 监听滚动，判断哪个元素在中间
			handleScroll() {
				return
				const query = uni.createSelectorQuery().in(this);
				const windowHeight = uni.getSystemInfoSync().windowHeight;

				this.data.forEach((item, index) => {
					const id = `media-${index}`;
					query.select(`#${id}`).boundingClientRect((rect) => {
						if (rect) {
							const centerY = rect.top + rect.height / 2;
							// 判断 centerY 是否位于窗口高度的 40% 到 60% 之间，以确定元素是否处于视口中心。
							const isCenter = centerY > windowHeight * 0.4 && centerY < windowHeight * 0.6;

							if (isCenter && !item.isPlaying) {
								this.$set(this.data, index, {
									...item,
									isPlaying: true
								});
								this.$nextTick(() => {
									this.initVideoPlayer(`video-${index}`, item);
								});
							} else if (!isCenter && item.isPlaying) {
								this.$set(this.data, index, {
									...item,
									isPlaying: false
								});
								this.destroyPlayer(`video-${index}`);
							}
						}
					}).exec();
				});
			},

			// 初始化播放器
			initVideoPlayer(idSelector, item) {
				const container = document.getElementById(idSelector);
				if (!container) return;

				const clips = [
					[60, 70], // 第一个片段：1分钟 - 1分10秒
					[100, 110],
					[160, 170],
					[200, 210],
					[220, 260]
				];

				let currentClipIndex = 0; // 记录当前播放片段索引

				const dp = new DPlayer({
					container: container,
					autoplay: true, // 自动播放
					muted: true, // 静音播放，防止浏览器阻止自动播放
					theme: "#000",
					loop: false, // DPlayer 自己循环，我们自己控制片段循环
					lang: "zh-cn",
					airplay: true,
					screenshot: false,
					hotkey: false,
					preload: "auto", // 预加载
					volume: 0,
					mutex: false, //允许多个播放器同时播放
					video: {
						url: item.video,
						pic: item.img,
						type: "customHls",

						customType: {
							customHls: function(video) {
								if (Hls.isSupported()) {
									const hls = new Hls();
									hls.loadSource(video.src);
									hls.attachMedia(video);
								} else if (video.canPlayType("application/vnd.apple.mpegurl")) {
									video.src = item.video;
								}
							},
						},
						playsInline: true, //允许在内嵌模式下播放
					},
				});
				dp.video.setAttribute("muted", "true");
				dp.video.setAttribute("playsinline", "true");

				dp.on('loadedmetadata', () => {
					dp.video.currentTime = clips[currentClipIndex][0]; // 跳到第一个片段
					dp.play();
				});

				dp.on('timeupdate', () => {
					const currentTime = dp.video.currentTime;
					const [start, end] = clips[currentClipIndex];

					if (currentTime >= end) {
						// 跳转到下一个片段
						currentClipIndex = (currentClipIndex + 1) % clips.length;
						dp.video.currentTime = clips[currentClipIndex][0];
						dp.play();
					}
				});

				this.videoPlayers[idSelector] = dp;
			},

			// 销毁播放器
			destroyPlayer(idSelector) {
				if (this.videoPlayers[idSelector]) {
					this.videoPlayers[idSelector].destroy();
					delete this.videoPlayers[idSelector];
				}
			},
		},
	};
</script>

<style scoped lang="scss">
	.tow-column-container {

		/* 页面滚动容器 */
		.container {
			width: 100vw;
			height: 100vh;
			overflow-y: auto;
			display: flex;
			justify-content: center;
		}

		/* 两列网格布局 */
		.grid {
			display: grid;
			grid-template-columns: repeat(2, 1fr);
			gap: 20rpx;
			padding: 20rpx;
		}

		/* 每个媒体项 */
		.media-item {
			/* 	width: 100%;
			height: 200px;
			display: flex;
			justify-content: center;
			align-items: center; */
			width: 100%;

			.img {
				width: 100%;
				height: 200rpx;
				border-radius: 15rpx;
			}

			.media {
				width: 100%;
				height: 200rpx;
				object-fit: cover;
				border-radius: 15rpx;
			}

			.name {
				text-align: center;
				font-size: var(--title-size);
			}
		}

		/* 视频容器 */
		.video-container {
			width: 100%;
			height: 100%;
			position: relative;
			overflow: hidden;
		}

		/* 隐藏DPlayer的控制栏 */

	}

	::v-deep .video-container .dplayer-controller {
		display: none !important;
	}

	.fixed-search {
		position: fixed;
		top: 80rpx;
		left: 0;
		right: 0;
		z-index: 10;
		/* 确保搜索栏在最上层 */
		background-color: #fff;
		/* 根据需要设置背景颜色 */
		padding: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
		/* 可选：添加阴影效果 */
	}
</style>